package com.scau.bookstore.api.interceptor;

import com.scau.bookstore.api.annotation.PassToken;
import com.scau.bookstore.api.annotation.LoginAuthToken;
import com.scau.bookstore.api.exception.AuthException;
import com.scau.bookstore.api.exception.TokenException;
import com.scau.bookstore.api.util.JwtUtil;
import com.scau.bookstore.common.pojo.User;
import com.scau.bookstore.contract.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }

        // 获取token里的信息
        String token = request.getHeader("X-Token");// 从 http 请求头中取出 token
        if (null == token) {
            throw new TokenException("token不能为空");
        }
        Long userId = JwtUtil.getIdByToken(token);
        User user = userService.findById(userId);
        if (user == null) {
            throw new TokenException("token已失效, 请重新登录");
        }

        //检查有没有需要用户登录的注解
        if (method.isAnnotationPresent(LoginAuthToken.class)) {
            LoginAuthToken loginAuthToken = method.getAnnotation(LoginAuthToken.class);
            if (loginAuthToken.required()) {
                return true;
            }
        }

        // 检查管理员权限(其余接口默认需要管理员权限才能访问)
        if (user.getRoleId() == null || user.getRoleId() == 1) {   // 非管理员
            throw new AuthException("无权限访问");
        }

        return true;
    }
}
